package sz.szsmk.citizencard.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.DefaultLayoutHelper;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.chenenyu.router.annotation.Route;
import com.google.gson.Gson;

import java.util.LinkedList;
import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.MineFragmentBinding;
import sz.szsmk.citizencard.dialog.TwoButtonDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonFragmentComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.response.FirstSearchUserLevelRes;
import sz.szsmk.citizencard.model.network.bean.response.GetOrderOpenidRes;
import sz.szsmk.citizencard.model.network.bean.response.GetTokenRes;
import sz.szsmk.citizencard.model.network.bean.response.HomeWhxfRes;
import sz.szsmk.citizencard.model.network.bean.response.IUserInfo;
import sz.szsmk.citizencard.model.network.bean.response.QueryAllFunctionNewRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryNgFinanceRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryOrderCountRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryPageResourceRes;
import sz.szsmk.citizencard.model.network.bean.response.SeleciUserAuthRes;
import sz.szsmk.citizencard.model.network.bean.response.SignInRes;
import sz.szsmk.citizencard.model.network.bean.response.UserCardFavResponse;
import sz.szsmk.citizencard.mvp.contract.IMineContact;
import sz.szsmk.citizencard.mvp.presenter.APPHomePresenter;
import sz.szsmk.citizencard.mvp.presenter.IMinePresenter;
import sz.szsmk.citizencard.ui.adapter.OrderAdapter;
import sz.szsmk.citizencard.ui.adapter.UserCardViewAdapter;
import sz.szsmk.citizencard.ui.adapter.UserHeadAdapter;
import sz.szsmk.citizencard.ui.adapter.UserListAdapter;
import sz.szsmk.citizencard.ui.adapter.UserOrderAdapter;
import sz.szsmk.citizencard.ui.adapter.UserWhxfAdapter;
import sz.szsmk.citizencard.ui.adapter.bean.AppHomeCardBean;
import sz.szsmk.citizencard.model.network.bean.response.CouponListBean;
import sz.szsmk.citizencard.ui.base.IBaseFragment;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpThirdView;
import sz.szsmk.citizencard.util.JumpUtils;

@SuppressLint("ValidFragment")
@Route("mine")
public class UserFragment extends IBaseFragment<IMinePresenter, MineFragmentBinding>
        implements IMineContact.IMineView, View.OnClickListener {
    private String mTitle;
    private RecyclerView userRv;
    private List<DelegateAdapter.Adapter> adapters;
    private UserCardViewAdapter userCardViewAdapter;
    private UserHeadAdapter userHeadAdapter;
    private String access_token;
    private String extend;
//    private UserGridAdapter userGridAdapter;
    private UserOrderAdapter userOrderAdapter;
    private UserWhxfAdapter whxfAdapter;
    private OrderAdapter orderAdapter;
    private UserListAdapter userListAdapter;
    private AppHomeCardBean homeCardBean;

    public static UserFragment getInstance() {
        UserFragment sf = new UserFragment();
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected int attachLayoutRes() {
        return R.layout.mine_fragment;
    }

    @Override
    protected void initInjector() {
        DaggerCommonFragmentComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        userRv = dataBinding.userRv;
        ACache.get(getActivity()).remove("mextend");
        access_token = ACache.get(getActivity()).getAsString("access_token");

    }

    private void initLayout() {
        mPresenter.getUserAdver();
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return true;
            }
        };

        userRv.setLayoutManager(layoutManager);
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        userRv.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 30);
        DelegateAdapter delegateAdapter = new DelegateAdapter(layoutManager, true);
        userRv.setAdapter(delegateAdapter);
        userRv.clearOnScrollListeners();
        userRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                userHeadAdapter.invalidateHead();
            }
        });
        adapters = new LinkedList<>();

        //头部适配器
        DefaultLayoutHelper headHelper = new DefaultLayoutHelper();
        userHeadAdapter = new UserHeadAdapter(getActivity(), headHelper, dataBinding.backView);
        userHeadAdapter.setBaseInterface(new UserHeadAdapter.BaseInterface() {
            @Override
            public void onClick(View view, String url, String syslabl, int need_header, String s, QueryAllFunctionNewRes.ClassListBean.FunctionListBean bean) {
                APPHomePresenter appHomePresenter = DaggerApplication.getAppHomePresenter();
                JumpThirdView.toNewJumpView(mContext, url, bean.getSys_label(), bean.getNeed_header(), appHomePresenter , bean.getFunction_id()+"",bean);
            }
        });
        adapters.add(userHeadAdapter);

        //订单适配器
        DefaultLayoutHelper defaultLayoutHelper = new DefaultLayoutHelper();
        userOrderAdapter = new UserOrderAdapter(getActivity(), defaultLayoutHelper);
//        adapters.add(userOrderAdapter);

        orderAdapter = new OrderAdapter(getActivity(), defaultLayoutHelper);
        adapters.add(orderAdapter);

//        //卡片适配器
        DefaultLayoutHelper cardHelper = new DefaultLayoutHelper();
        userCardViewAdapter = new UserCardViewAdapter(getActivity(), cardHelper);
        adapters.add(userCardViewAdapter);

        userListAdapter = new UserListAdapter(getActivity(), defaultLayoutHelper);
        userListAdapter.moreOnClick(new UserListAdapter.MoreInterface() {
            @Override
            public void onClick(View view, int position, String type) {
                mPresenter.getOrderOpenid(type);
            }
        });
        userListAdapter.setBaseInterface(new UserListAdapter.BaseInterface() {
            @Override
            public void onClick(View view, String type) {

                if (type.equals("sb")) {

                    String url = Constant.BASE_URL + "app-front-end/#/fundAndSociety/authPage?access_token=" + access_token + "&type=1&name=" + homeCardBean.getCustName();

                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    JumpUtils.jumptoNatvie(getActivity(), "webView", 0, bundle);
                } else if (type.equals("gjj")) {

                    String url = Constant.BASE_URL + "app-front-end/#/fund/main?access_token=" + access_token ;

                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    JumpUtils.jumptoNatvie(getActivity(), "webView", 0, bundle);
                } else if (type.equals("ghf")) {

                    //跳转桂花分
                    Bundle bundle = new Bundle();
                    String murl = Constant.SZ_URL +"?"+ Constant.EXTENT;
                    bundle.putString("url", murl);
                    bundle.putString(Constant.TITLE, "桂花分");
                    JumpUtils.jumptoNatvie(mContext, "webView", 0, bundle);
                }

            }
        });
        adapters.add(userListAdapter);

        delegateAdapter.setAdapters(adapters);

        mPresenter.queryOrderCount();
        mPresenter.selectUserAuth();
        mPresenter.queryNgFinance("1");

    }


    @Override
    protected void updateViews() {

    }


    @Override
    public void updataError(IUserInfo message) {
        if (message.getCode().equals("000016") || message.getCode().equals("000002")) {

            final TwoButtonDialog dialog = new TwoButtonDialog(getActivity(), message.getMessage());
            dialog.setOnOkClickListener(new TwoButtonDialog.OnOkClickListener() {
                @Override
                public void onOkClick() {
                    JumpUtils.jump(mContext, "login", 0);
                    dialog.cancel();
//                    getActivity().finish();
                }
            });
            dialog.setOnCancelClickListener(new TwoButtonDialog.OnCancelClickListener() {
                @Override
                public void onCancelClick() {
                    ACache.get(DaggerApplication.getIns()).remove("access_token");
                    dialog.cancel();
                }
            });
            dialog.show();


        }
    }

    @Override
    public void getUserInfoSucc(IUserInfo response) {
        if (response == null) {
            return;
        }
        IUserInfo.UserExBean userEx = response.getUserEx();
        if (userEx != null) {
            userHeadAdapter.setListData(userEx);
            String json = new Gson().toJson(userEx);
            ACache.get(DaggerApplication.getIns()).put("userinfo", json);
            userHeadAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void getUserInfoFail(IUserInfo response) {
        String code = response.getCode();
        if (code.equals("000016")) {
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initLayout();
        String access_token = ACache.get(mContext).getAsString("access_token");
        mPresenter.getWhxfInfo();
        if (access_token != null) {
            mPresenter.getOrderOpenid(access_token);
            mPresenter.queryUserCredit();
            mPresenter.queryCouponCountSucc();
            mPresenter.selectUserAuth();
        }
        mPresenter.getUserInfo();
        mPresenter.queryUserCardFav();
        mPresenter.firstSearchUserLevel();
    }

    @Override
    public void queryUserCardFavSucc(List<UserCardFavResponse.DataBean> beanList) {
        userCardViewAdapter.setCardData(beanList);
        userCardViewAdapter.notifyDataSetChanged();
    }

    @Override
    public void queryUserCardFavFaile() {

    }

    @Override
    public void getWhxfInfoSucc(List<HomeWhxfRes.CultureInforsBean> cultureInfors) {
        userCardViewAdapter.setWhxfData(cultureInfors);
        userCardViewAdapter.notifyDataSetChanged();
    }

    @Override
    public void getWhxfInfoFail() {

    }

    @Override
    public void getUserAdverSucc(QueryPageResourceRes response) {
        List<QueryPageResourceRes.ResourceListBean> resource_list = response.getResource_list();
        if (resource_list != null) {
            userCardViewAdapter.setAdaverData(resource_list);
            userCardViewAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void getUserAdverFail() {

    }

    @Override
    public void getAccessTokenFail() {

    }

    @Override
    public void getAccessTokenSucc(GetTokenRes response) {

    }

    @Override
    public void getOrderOpenidFail() {

    }

    @Override
    public void getOrderOpenidSucc(GetOrderOpenidRes response, String type) {
        if (type.equals("ghf")) {
            String url = Constant.SZ_URL +"?"+ response.getExtend();
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            bundle.putString(Constant.TITLE, "桂花分");
            JumpUtils.jumptoNatvie(mContext, "webView", 0, bundle);
        } else {
            extend = response.getExtend();
            userOrderAdapter.setOrderExtent(extend);
            userOrderAdapter.notifyDataSetChanged();

            userCardViewAdapter.setExtent(extend);
            userCardViewAdapter.notifyDataSetChanged();
            ACache.get(getActivity()).remove("extend");
            ACache.get(getActivity()).put("extend", extend);
        }
    }

    @Override
    public void queryOrderCountFail(QueryOrderCountRes response) {
    }

    @Override
    public void queryOrderCountSucc(QueryOrderCountRes response) {
        orderAdapter.setViewData(response);
        orderAdapter.notifyDataSetChanged();
    }

    @Override
    public void selectUserAuthSucc(SeleciUserAuthRes response) {
        Constant.isLogin = false;
        userListAdapter.setViewData(response.getAuthTypeList());
        userListAdapter.notifyDataSetChanged();
    }

    @Override
    public void selectUserAuthFail() {

    }

    @Override
    public void seleUnlogin(IUserInfo response) {
        Constant.isLogin = false;
        userHeadAdapter.notifyDataSetChanged();
        final TwoButtonDialog dialog = new TwoButtonDialog(getActivity(), response.getMessage());
        if (response.getCode().equals("000016")) {
            dialog.setOnOkClickListener(new TwoButtonDialog.OnOkClickListener() {
                @Override
                public void onOkClick() {
                    ACache.get(getActivity()).remove("access_token");
                    dialog.cancel();
                }
            });
            dialog.setOnCancelClickListener(new TwoButtonDialog.OnCancelClickListener() {
                @Override
                public void onCancelClick() {
                    ACache.get(getActivity()).remove("access_token");
                    ACache.get(getActivity()).remove("mextend");
                    JumpUtils.jump(mContext, "login", 0);
                    dialog.cancel();
//                    getActivity().finish();
                }
            });
            dialog.show();
        }

    }

    @Override
    public void firstSearchUserLevelFail(FirstSearchUserLevelRes response) {

    }

    @Override
    public void firstSearchUserLevelSucc(AppHomeCardBean appHomeCardBean) {
        homeCardBean = appHomeCardBean;
        userListAdapter.setLvdata(homeCardBean);
//        userListAdapter.setLevelData(appHomeCardBean.getLevel());
        userListAdapter.notifyDataSetChanged();


        userHeadAdapter.setLvdata(homeCardBean);
    }

    @Override
    public void queryUserCreditSucc(SignInRes userCreditBean) {
        //获取用户当前总积分 返回
        if (userCreditBean == null) {
            return;
        }
        userHeadAdapter.setUserCreditBean(userCreditBean);
        userHeadAdapter.notifyDataSetChanged();
    }
    @Override
    public void queryCouponCountSucc(CouponListBean couponListBean) {
        //优惠券 返回
        if(couponListBean!=null){
            userHeadAdapter.setCounpon(couponListBean);
            userHeadAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void queryNgFinanceSucc(QueryNgFinanceRes queryNgFinanceRes) {
        userHeadAdapter.setQueryNgFinanceRes(queryNgFinanceRes);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }
}